<template>
  <transition enter-active-class="animated fadeInRight">
    <div class="call-taxi">
      <div id="container"></div>
      <div class="top">
        <div class="back" @click="back"></div>
      </div>
      <div class="content">
        <span class="line"></span>
        <div class="taxi taxi-selected">
          <div>
            <span style="font-weight: bold;font-size: 20px;line-height: 30px">快车</span>
            <br>
            <span style="font-size: 12px;border: solid #999 1px;color:#999;padding: 1px;border-radius: 3px;">省时省事省心</span>
          </div>
          <div style="position: absolute;right: 20px;top: 15px;">
            <p style="font-size: 12px">预估 <span style="font-size: 28px;font-weight: bold">{{price}}</span>元</p>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="btn" @click="callTaxi">确认呼叫 快车</div>
      </div>
<!--      <div id="panel"></div>-->
    </div>
  </transition>
</template>
<script>
import {mapState} from 'vuex'
import computePrice from '@/components/computePrice'
import amap from '@/components/public/amap.vue'
import tip from '@/components/tip'
import Icon from "vue-awesome/components/Icon"
import {dispatch, orderForecast} from "../../api";

export default {
  data(){
    return{
      price: 0.0
    }
  },
  computed: {
    ...mapState([
      'position',
      'address'
    ])
  },
  components: {
    tip,
    computePrice,
    amap
  },
  created() {

  },
  mounted() {
    let _this = this
    var map = new AMap.Map("container", {
      resizeEnable: true,
      zoom: 14
    });

    AMap.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：5s
        buttonPosition:'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 30),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showCircle: false
        // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

      });
      map.addControl(geolocation);
    });

    var drivingOption = {
      policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
    }

    // 构造路线导航类
    var driving = new AMap.Driving(drivingOption)

    // 根据起终点经纬度规划驾车导航路线
    driving.search(new AMap.LngLat(_this.$store.state.startLocation.lng, _this.$store.state.startLocation.lat), new AMap.LngLat(_this.$store.state.endLocation.lng, _this.$store.state.endLocation.lat), function(status, result) {
      // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
      if (status === 'complete') {
        if (result.routes && result.routes.length) {
          // 绘制第一条路线，也可以按需求绘制其它几条路线
          drawRoute(result.routes[0])
          console.log('绘制驾车路线完成')
        }
      } else {
        console.log('获取驾车数据失败：' + result)
      }
    });

    function drawRoute (route) {
      var path = parseRouteToPath(route)

      var startMarker = new AMap.Marker({
        position: path[0],
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
        map: map
      })

      var endMarker = new AMap.Marker({
        position: path[path.length - 1],
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
        map: map
      })

      var routeLine = new AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: '#ffeeee',
        borderWeight: 2,
        strokeWeight: 5,
        strokeColor: '#18a33e',
        lineJoin: 'round'
      })

      routeLine.setMap(map)

      // 调整视野达到最佳显示区域
      map.setFitView([ startMarker, endMarker, routeLine ])
    }

    // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
    // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
    function parseRouteToPath(route) {
      var path = []

      for (var i = 0, l = route.steps.length; i < l; i++) {
        var step = route.steps[i]

        for (var j = 0, n = step.path.length; j < n; j++) {
          path.push(step.path[j])
        }
      }
      return path
    }

    // 预估价格
    orderForecast({
      params: {
        'startLongitude': _this.$store.state.startLocation.lng,
        'startLatitude': _this.$store.state.startLocation.lat,
        'targetLongitude': _this.$store.state.endLocation.lng,
        'targetLatitude': _this.$store.state.endLocation.lat
      }
    }).then(data => {
      _this.price = Math.ceil(data.result * 10) / 10
    }).error(err => {

    })

  },
  methods: {
    back(){
      this.$store.state.address.start = null
      this.$store.state.address.end = null
      this.$router.push({path: '/'})
    },
    callTaxi: function () {
      let _this = this
      console.log(_this.$store.state.passengerPosition.lat)
      let params = new URLSearchParams()
      params.append('passengerInfoId', _this.$store.state.userInfo.id)
      params.append('passengerPhone', _this.$store.state.userInfo.phone)
      params.append('userLongitude', _this.$store.state.passengerPosition.lng.toString())
      params.append('userLatitude', _this.$store.state.passengerPosition.lat.toString())
      params.append('startLongitude', _this.$store.state.startLocation.lng.toString())
      params.append('startLatitude', _this.$store.state.startLocation.lat.toString())
      params.append('startAddress', _this.$store.state.address.start)
      params.append('endAddress', _this.$store.state.address.end)
      params.append('endLongitude', _this.$store.state.endLocation.lng.toString())
      params.append('endLatitude', _this.$store.state.endLocation.lat.toString())
      params.append('passengerToken', _this.$store.state.userInfo.token)
      console.log(params)
      dispatch(params)
      .then(res => {
        if (res.success === true) {
          _this.$store.state.order = res.result
          this.$router.push({path: '/order/loader'})
        }
      })
      .catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
<style scoped>
  .suggest{
    position: relative;
    z-index: 999;
    height: 100%;
    animation-duration: .5s;
  }
  .amap{
    height: 94%;
    width: 100%;
    position: absolute;
    z-index: 800;
    /*background-color: green;*/
  }
  .mint-popup.mint-popup-right{
    width: 100%;
    height: 100%;
    background-color: #f3f4f5;
  }
  #container{
    position: fixed;
    top: 0;
    z-index: 1;
    height: 38%;
  }
  .top{
    width: 100%;
    height: 40px;
    background-color: #CCC;
  }
  .back{
    width: 30px;
    height: 30px;
    background-color: #FFF;
    border-radius: 30px;
    position: fixed;
    top: 5px;
    left: 10px;
    z-index: 99;
    box-shadow: 0 1px 15px rgba(69, 68, 68, 0.1);
  }
  .content{
    z-index: 99;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 65%;
    background-color: #FFF;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .content .line{
    margin: 0 auto;
    margin-top: 5px;
    margin-bottom: 10px;
    display: block;
    width: 35px;
    height: 2px;
    border-radius: 1px;
    background-color: #CCC;
  }
  .content .taxi{
    width: 88%;
    padding: 15px 15px 15px 15px;
    margin: 0 auto;
    border-bottom: solid #e8e8e8 1px;
    position: relative;
  }
  .content .taxi-selected{
    background-color: rgba(26, 119, 189, 0.1);
    border-radius: 8px;
  }
  .footer{
    z-index: 999;
    position: fixed;
    bottom: 0;
    height: 100px;
    width: 100%;
    box-shadow: 0 1px 15px rgba(0,0,0,.2);
  }
  .footer .btn{
    width: 90%;
    position: relative;
    top: 30px;
    padding-top: 10px;
    padding-bottom: 10px;
    background-color: #1b3463;
    box-shadow: 0 0px 15px rgba(28,56,108,.6);
    color: #FFF;
    margin: 0 auto;
    border-radius: 5px;
  }
</style>
